package com.hc.controller;

import com.hc.domain.Category;
import com.hc.service.CategoryService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.validation.Valid;

@Controller
@RequestMapping("/category")
public class CategoryController {

    @Resource
    private CategoryService categoryService;

    //@GetMapping("/list")
    //public String list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
    //                   @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
    //                   @ModelAttribute("msg") String msg, //接收请求转发过来的提示信息
    //                   Model model) {
    //    PageBean<Category> categoryIPage = categoryService.getCategoriesWithPage(pageNum, pageSize);
    //    if(msg == null) {
    //        model.addAttribute("msg", "恭喜，查询成功！");
    //    }
    //    model.addAttribute("data", categoryIPage);
    //    return "/admin/category";
    //}

    @GetMapping("/showAdd")
    public String showAdd(Model model) {
        model.addAttribute("category", new Category());//数据回显时用
        return "/admin/category-add-update";
    }

    @PostMapping("/add")
    public String add(@Valid Category category, BindingResult result, RedirectAttributes attributes, Model model) {

        return "redirect:/admin/category/list";
    }

    @GetMapping("/showUpdate/{id}")
    public String showUpdate(@PathVariable("id") Integer id, Model model) {
        //Category category = categoryService.getCategoryById(id);
        //model.addAttribute("category",category);
        return "admin/category-add-update"; //跳转到编辑页面（编辑和增加使用同一个页面）
    }

    @PostMapping("/update/{id}")
    public String update(@PathVariable("id") Integer id, @Valid Category category, BindingResult result, RedirectAttributes attributes) {

        return "redirect:/admin/category/list";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id, RedirectAttributes attributes) {
        int deleteRes = categoryService.deleteCategoryById(id);
        if (deleteRes == 1) {
            attributes.addFlashAttribute("msg", "恭喜，删除成功！");
        } else {//失败
            attributes.addFlashAttribute("msg", "恭喜，删除失败！");
        }
        return "redirect:/admin/category/list";
    }
}
